//
//  HomeTabVC.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/10/25.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "HomeTabVC.h"
#import "HomeTabVCHeaderView.h"
#import "HomeFunctionCell.h"
#import "HomeSectionCell.h"
#import "SubjectRecommendCell.h"
#import "DemandCell.h"
#import "ServiceCell.h"
#import "SubjectRecommendContentTabVC.h"
#import "SubjectDemandServiceTabVC.h"
#import "ServiceContentTabVC.h"
#import "DemandTheHallContentVC.h"
#import "HomeModel.h"
#import "SearchView.h"
#import "HomeSearchVC.h"
#import "MyMessageTabVC.h"
#import "ServiceModel.h"
#import "SpecialRecommendationModel.h"
#import "SubjectRecommendModel.h"
#import "FunctionVC.h"
#import "WRNavigationBar.h"
@interface HomeTabVC
()<HomeFunctionCellDelegate,SubjectRecommendCellDelegate,HomeSectionCellDelegate,DemandCellDelegate,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
@property(nonatomic,strong) HomeTabVCHeaderView *homeHeaderView;
@property(nonatomic,strong) UIButton *preBtn;
@property(nonatomic,strong) HomeModel *homeModel;
@property(nonatomic,strong) NSMutableArray *demandArray;
@property(nonatomic,strong) NSMutableArray *serveArray;
@property(nonatomic,strong) NSMutableArray *subjectDemandArray;
@property(nonatomic,strong) NSMutableArray *subjectServiceArray;
@property(nonatomic,strong) NSMutableArray *subjectRecommendMuta;
@property(nonatomic,strong) NSIndexPath *preIndexPath;
@property(nonatomic,strong) HomeModel *preModel;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) NSString *urlString;
@property(nonatomic,strong) NSDictionary *dict;
@property(nonatomic,assign) NSInteger pageNumber;
@property(nonatomic,assign) NSInteger pageSize;
@property(nonatomic,strong) NSIndexPath *indexPath;
@property(nonatomic,strong) UIButton *checkBtn;
@property(nonatomic,assign) NSInteger changeInternet;
@property(nonatomic,assign) BOOL autoReloadInternet;
@end

@implementation HomeTabVC
-(NSMutableArray *)demandArray
{
    if (!_demandArray) {
        _demandArray = [NSMutableArray array];
       
    }
    return _demandArray;
}
-(NSMutableArray *)serveArray
{
    if (!_serveArray) {
        _serveArray = [NSMutableArray array];
        
    }
    return _serveArray;
}
-(NSMutableArray *)subjectDemandArray
{
    if (!_subjectDemandArray) {
        _subjectDemandArray = [NSMutableArray array];
        
    }
    return _subjectDemandArray;
}
-(NSMutableArray *)subjectServiceArray
{
    if (!_subjectServiceArray) {
        _subjectServiceArray = [NSMutableArray array];
        
    }
    return _subjectServiceArray;
}
//
-(NSMutableArray *)subjectRecommendMuta
{
    if (!_subjectRecommendMuta) {
        _subjectRecommendMuta = [NSMutableArray array];
        
    }
    return _subjectRecommendMuta;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager = [AFHTTPSessionManager manager];
    self.pageNumber = 1;
    self.pageSize = 2;
//    self.changeInternet = 1;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedRowHeight = 0;
    self.edgesForExtendedLayout = UIRectEdgeTop;
    self.tableView.contentInset = UIEdgeInsetsMake(-kNavAndStatusHight, 0, 0, 0);
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    SearchView *searchView = [[SearchView alloc]initWithFrame:CGRectMake(0, 0, self.navigationController.navigationBar.bounds.size.width, self.navigationController.navigationBar.bounds.size.height-8)];
        __weak typeof (self)weakSelf = self;
        searchView.returnValueBlock = ^(NSInteger selected) {
            if (selected == 0) {
                XLog(@"returnValueBlock");
                HomeSearchVC *searchVC = [[HomeSearchVC alloc]init];
                [weakSelf.navigationController pushViewController:searchVC animated:YES];
            }else {
                MyMessageTabVC *myMsgVC = [[MyMessageTabVC alloc]init];
                [weakSelf.navigationController pushViewController:myMsgVC animated:YES];
            }
            XLog(@"selected:%ld",selected);
    };
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:searchView];
    
    // 设置导航栏颜色
    [self wr_setNavBarBarTintColor:[UIColor colorWithRed:229/255.0 green:229/255.0 blue:229/255.0 alpha:1]];
    [self wr_setNavBarBackgroundAlpha:0];
    self.homeHeaderView = [[HomeTabVCHeaderView alloc]initWithFrame:CGRectMake(0, 0, kVWidth, kVWidth/750*458)];
    self.preModel = [[HomeModel alloc]init];
    self.tableView.tableHeaderView = self.homeHeaderView;
    [self reloadInternetData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(insertCollection:) name:@"insertCollection" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeInternet:) name:@"changeInternet" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logIn:) name:@"logIn" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logInOut:) name:@"logInOut" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(collectDemandContent:) name:@"collectDemandContent" object:nil];
//    if (self.changeInternet != 0) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self chectVersion];        
    });
//    }
}

#pragma mark-代理:检测版本
-(void)chectVersion
{
    NSString *currentTime = [TimeHelper currentZeroTime];
    XLog(@"currentTime:%@",currentTime);
    XLog(@"currentTime:%ld",(long)[currentTime integerValue]);
    NSTimeInterval nextTime = [TimeHelper whichTime:@"2019/2/20"];
    if ([currentTime integerValue]>nextTime ) {
        NSTimer *timer = [NSTimer timerWithTimeInterval:0 target:self selector:@selector(timerAction:) userInfo:nil repeats:NO];
        XLog(@"nextTime:%f",nextTime);
        if (self.changeInternet != 0) {
            [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
        }
    }
}
-(void)timerAction:(NSTimer *)sender
{
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    
        NSString *getLocalVersion = [CheckVersion getAPPInfo];
        //最新的获取数据的地址：
        NSString *appID=@"1441941518";
        //https://itunes.apple.com/lookup?id=1441941518
        NSString *urlStr=[NSString stringWithFormat:@"https://itunes.apple.com/lookup?id=%@",appID];
        NSURL *url=[NSURL URLWithString:urlStr];
        NSData *json = [NSData dataWithContentsOfURL:url];
        //        XLog(@"json:%@",json);
        NSDictionary *dictVersion = [NSJSONSerialization JSONObjectWithData:json options:0 error:NULL];//解析json文件
        XLog(@"dictVersion:%@",dictVersion);
        NSArray *results = [dictVersion objectForKey:@"results"];
        NSDictionary *dictSub = results[0];
        XLog(@"results:%@",results);
        NSString  *message = [dictSub objectForKey:@"releaseNotes"];
        NSString *version = [dictSub objectForKey:@"version"];
        XLog(@"version:%@",version);
        if (![version isEqualToString:getLocalVersion]) {
            TYAlertView *alertView = [TYAlertView alertViewWithTitle:[NSString stringWithFormat:@"%@%@",[NSBundle bundleLocalizedStringForKey:@"newVersion"],version] message:@""];
            alertView.messageLabel.text = message;
            alertView.messageLabel.textAlignment = NSTextAlignmentJustified;
            [alertView addAction:[TYAlertAction actionWithTitle:[NSBundle bundleLocalizedStringForKey:@"nowUpdate"] style:TYAlertActionStyleDefault handler:^(TYAlertAction *action) {
                // 1441941518
                //                NSString *str = urlStr //更换id即可
                //https://itunes.apple.com/cn/app/id1441941518
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSBundle bundleLocalizedStringForKey:@"updateUrl"]]];
                //XLog(@"%@",action.title);
            }]];
            TYAlertController *alertController = [TYAlertController alertControllerWithAlertView:alertView preferredStyle:TYAlertControllerStyleAlert transitionAnimation:TYAlertTransitionAnimationDropDown];
            [self presentViewController:alertController animated:YES completion:nil];
        }
//    });
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY >= kVWidth/750*458-kNavAndStatusHight)
    {
        CGFloat alpha = (offsetY-kVWidth/750*458-kNavAndStatusHight) / kNavAndStatusHight+kStatusBarHeight*2;
        [self wr_setNavBarBackgroundAlpha:alpha];
        XLog(@"offsetY-kVWidth/750*458-kNavAndStatusHight:%f",offsetY-kVWidth/750*458-kNavAndStatusHight);
        XLog(@"kNavAndStatusHight+kStatusBarHeight:%f",kNavAndStatusHight+kStatusBarHeight*2);
    }else {
        [self wr_setNavBarBackgroundAlpha:0];
    }
    
}
-(void)logIn:(NSNotification *)info
{
    [self reloadInternet];
}
-(void)logInOut:(NSNotification *)info
{
    [self reloadInternet];
}
#pragma mark-代理:搜藏后刷新
-(void)collectDemandContent:(NSNotification *)info
{
    [self.demandArray removeAllObjects];
    self.urlString = [NSString stringWithFormat:@"%@/demand/selectTwoDemand",kUrl];
    XLog(@"[UserDefaultsHelper readUid]:%@",[UserDefaultsHelper readUid]);
    self.dict = @{
                  @"pageNum":@"1",
                  @"pageSize":@"5",
                  @"token":[UserDefaultsHelper readToken],
                  @"uid":[UserDefaultsHelper readUid]
                  };
    [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        XLog(@"responseObject:%@",responseObject);
        NSArray *date = [responseObject objectForKey:@"date"];
        XLog(@"date:%@",date);
       
            XLog(@"最新需求responseObject:%@",responseObject);
            for (NSDictionary *dict in date) {
                HomeModel *model =[HomeModel mj_objectWithKeyValues:dict];
                [self.demandArray addObject:model];
            }
        NSIndexSet *set = [NSIndexSet indexSetWithIndex:4];
        [self.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationNone];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        XLog(@"网络error:%@",error);
        
    }];
}

-(void)reloadInternet
{
    
//    [self.serveArray removeAllObjects];
//    [self.subjectRecommendMuta removeAllObjects];
//    dispatch_async(dispatch_get_main_queue(), ^{
    [self.homeHeaderView reloadInternetData];
    [self reloadInternetData];
//    });
}
-(void)reloadInternetData
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
        [WSProgressHUD show];
//        [[AFNetworkReachabilityManager sharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//            switch (status) {
//                case AFNetworkReachabilityStatusUnknown:{
//                    XLog(@"未知");
//                    self.changeInternet = 0;
//                }
//                    break;
//                case AFNetworkReachabilityStatusNotReachable:{
//                    XLog(@"没有网络");
//                    self.changeInternet = 0;
//                }
//                    break;
//                case AFNetworkReachabilityStatusReachableViaWWAN:{
//                    XLog(@"3G/4G");
//                    self.changeInternet = 1;
//                }
//                    break;
//                case AFNetworkReachabilityStatusReachableViaWiFi: {
//                    XLog(@"无线网");
//                    self.changeInternet = 2;
//                }
//                    break;
//                default:
//                    break;
//            }
        
//        }];
//        [[AFNetworkReachabilityManager sharedManager] startMonitoring];
        XLog(@"self.changeInternet:%ld",(long)self.changeInternet);
                    //使用GCD的信号量 dispatch_semaphore_t 创建同步请求
            dispatch_group_t group =dispatch_group_create();
            dispatch_queue_t globalQueue=dispatch_get_global_queue(0, 0);
            dispatch_semaphore_t semaphore= dispatch_semaphore_create(0);
            dispatch_group_async(group, globalQueue, ^{
                for (int i = 0; i<4; i++) {
                    NSString *pageNumber = [NSString stringWithFormat:@"%ld",self.pageNumber];
                    NSString *pageSize = [NSString stringWithFormat:@"%ld",self.pageSize];
                    if (i == 0) {//专题推荐
                        self.urlString = [NSString stringWithFormat:@"%@/recommend/selectTowDemandRecommend",kUrl];
                        self.dict = @{
                                      @"pageNumber":pageNumber,
                                      @"pageSize":pageSize,
                                      @"uid":[UserDefaultsHelper readUid],
                                      @"token":[UserDefaultsHelper readToken]
                                      };
                    }else if (i == 1) {//最新需求
                        self.urlString = [NSString stringWithFormat:@"%@/demand/selectTodayDemand",kUrl];
                        XLog(@"[UserDefaultsHelper readUid]:%@",[UserDefaultsHelper readUid]);
                        self.dict = @{
                                      @"pageNum":@"1",
                                      @"pageSize":@"5",
                                      @"token":[UserDefaultsHelper readToken],
                                      @"uid":[UserDefaultsHelper readUid]
                                      };
                        XLog(@"最新需求:%@",self.dict);
                    }else if (i == 2) {//最新服务
                        self.urlString = [NSString stringWithFormat:@"%@/association/listNew",kUrl];
                        self.dict = @{
                                      @"page":@"1",
                                      @"rows":@"5",
                                      };
                    }else {//H5
                        self.urlString = [NSString stringWithFormat:@"%@/tools/selectAll",kUrl];
                        self.dict = nil;
                    }
                    [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                        XLog(@"responseObject:%@",responseObject);
                        NSArray *date = [responseObject objectForKey:@"date"];
                        XLog(@"date:%@",date);
                        if (i == 0) {
                            NSString *status = [responseObject objectForKey:@"status"];
                            if ([status integerValue] == 201) {
                                [LogOutAccount presentOutAccount];
                                [UIAlertViewWarningAccount showWarningAccount];
                                [self reloadInternet];
                            }
                            NSDictionary *date = [responseObject objectForKey:@"date"];
                            NSArray *demandList =[date objectForKey:@"demandList"];
                            NSArray *association =[date objectForKey:@"association"];
                            [self.subjectDemandArray removeAllObjects];
                            for (NSDictionary *dict in demandList) {
                                SpecialRecommendationModel *model =[SpecialRecommendationModel mj_objectWithKeyValues:dict];
                                [self.subjectDemandArray addObject:model];
                            }
                            [self.subjectServiceArray removeAllObjects];
                            for (NSDictionary *dict in association) {
                                SpecialRecommendationModel *model =[SpecialRecommendationModel mj_objectWithKeyValues:dict];
                                [self.subjectServiceArray addObject:model];
                            }
                        }else if (i == 1) {
                            [self.demandArray removeAllObjects];
                            XLog(@"最新需求responseObject:%@",responseObject);
                            for (NSDictionary *dict in date) {
                                HomeModel *model =[HomeModel mj_objectWithKeyValues:dict];
                                [self.demandArray addObject:model];
                            }
                        }else if (i == 2) {
                            XLog(@"最新服务responseObject:%@",responseObject);
                            [self.serveArray removeAllObjects];
                            for (NSDictionary *dict in date) {
                                ServiceModel *model = [ServiceModel mj_objectWithKeyValues:dict];
                                [self.serveArray addObject:model];
                                XLog(@"dict:%@",dict);
                            }
                        }else {
                            [self.subjectRecommendMuta removeAllObjects];
                            for (NSDictionary *dict in date) {
                                SpecialRecommendationModel *model =[SpecialRecommendationModel mj_objectWithKeyValues:dict];
                                [self.subjectRecommendMuta addObject:model];
                            }
                        }
                        
                        dispatch_semaphore_signal(semaphore);
                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                        XLog(@"网络error:%@",error);
                        self.tableView.emptyDataSetSource = self;
                        self.tableView.emptyDataSetDelegate = self;
                        //                NoDataView *noDataView = [[NoDataView alloc]initWithFrame:self.view.bounds];
                        //                [self.tableView addSubview:noDataView];
                        
                        dispatch_semaphore_signal(semaphore);
                    }];
                    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
                }
                
            });
            
            dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
                XLog(@"%@---Home全部结束。。。",[NSThread currentThread]);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [WSProgressHUD dismiss];
                    XLog(@"self.changeInternet:%ld",(long)self.changeInternet);
                    XLog(@"demandArray:%@",self.demandArray);
                    XLog(@"serveArray:%@",self.serveArray);
//                    if (self.changeInternet != 0) {
//                        if (!self.demandArray.count||!self.serveArray.count||!self.subjectServiceArray.count||!self.subjectDemandArray.count) {
//                            [self reloadInternet];
//                        }
//                    }
                    [self.tableView reloadData];
                });
            });
//        }
    });
}
-(void)changeInternet:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"changeInternetdict:%@",dict);
    self.changeInternet = [[dict objectForKey:@"changeInternet"]integerValue];
    XLog(@"self.changeInternet:%ld",self.changeInternet);
     if (self.changeInternet != 0) {
         [self reloadInternet];
     }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 7;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.changeInternet != 0) {
        if (section == 2) {
            return 2;
        }else if (section == 4) {
            return self.demandArray.count?self.demandArray.count:0;
        }else if (section == 6) {
            return self.serveArray.count?self.serveArray.count:0;
        }else {
            return 1;
        }
        
    }else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView  setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    UITableViewCell *cellDefault = [[UITableViewCell alloc]init];
    switch (indexPath.section) {
        case 0:
            {
                HomeFunctionCell *cell = [HomeFunctionCell cellClassWithTableView:tableView];
                cell.subjectRecommendArray = self.subjectRecommendMuta;
                cell.delegate = self;
                cellDefault = cell;
            }
            break;
        case 2:
        {
            SubjectRecommendCell *cell = [SubjectRecommendCell cellNibWithTableView:tableView];
            cell.delegate = self;
            cell.indexPath = indexPath;
            if (self.subjectDemandArray.count) {
                cell.subjectDemandArray = self.subjectDemandArray;
            }
            if (self.subjectServiceArray.count) {
                cell.subjectServiceArray = self.subjectServiceArray;
            }
            cellDefault = cell;
        }
            break;
        case 4:
        {
            DemandCell *cell = [DemandCell cellNibWithTableView:tableView];
            cell.delegate = self;
            cell.indexPath = indexPath;
            if (self.demandArray.count) {
                HomeModel *model = self.demandArray[indexPath.row];
                cell.homeModel = model;
            }
            cellDefault = cell;
        }
            break;
        case 6:
        {
            ServiceCell *cell = [ServiceCell cellNibWithTableView:tableView];
            if (self.serveArray.count) {
                XLog(@"self.serveArray:%@",self.serveArray);
                ServiceModel *model = self.serveArray[indexPath.row];
                cell.serviceModel = model;
            }
            cellDefault = cell;
        }
            break;
        default:
        {
            HomeSectionCell *cell = [HomeSectionCell cellClassWithTableView:tableView];
            cell.indexPath = indexPath;
            cell.delegate = self;
            cellDefault = cell;
        }
            break;
    }
    return cellDefault;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
         return 100;
    }else if (indexPath.section == 1||indexPath.section == 3||indexPath.section == 5){
        return 106;
    }else if(indexPath.section == 2){
        return 115;
    }else if(indexPath.section == 4){
        return 144;
    }else {
        return 124 ;
    }
}
#pragma mark-代理:功能入口
-(void)HomeFunctionCell:(HomeFunctionCell *)HomeFunctionCell withTag:(NSInteger)tag withTitle:(nonnull NSString *)title
{
    FunctionVC *homVC = [[FunctionVC alloc]init];
    homVC.navigationItem.title = title;
    homVC.subjectModel =  self.subjectRecommendMuta[tag];
    [self.navigationController pushViewController:homVC animated:YES];
}
#pragma mark-代理:专题推荐
-(void)subjectRecommendCell:(SubjectRecommendCell *)subjectRecommendCell withTag:(NSInteger)tag withIndexPath:(nonnull NSIndexPath *)indexPath withSpecialModel:(nonnull SpecialRecommendationModel *)specialModel
{

    SubjectRecommendContentTabVC *homeVC = [[SubjectRecommendContentTabVC alloc]init];
    __weak typeof (self)weakSelf = self;
    homeVC.returnValueBlock = ^(NSInteger selected) {
        specialModel.collectionStatus = [NumberSwitchString numberSwitchString:selected];
        [weakSelf reloadInternet];
    };
    XLog(@"indexPath.row:%ld",indexPath.row);
    homeVC.specialModel = specialModel;
    homeVC.index = indexPath.row;
    [self.navigationController pushViewController:homeVC animated:YES];

    
}
#pragma mark-代理:刷新专题推荐
- (void)HomeSectionCell:(HomeSectionCell *)HomeSectionCell withClickIndicatorBtn:(UIButton *)clickIndicatorBtn withIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        if (self.changeInternet == 0) {
            [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请检查网络设置"];
        }else {
            XLog(@"indexPath:%ld",(long)indexPath.section);
            self.pageNumber ++;
            if (self.pageNumber >2) {
                self.pageNumber=1;
            }
            self.subjectDemandArray = nil;
            self.subjectServiceArray = nil;
            [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
            [WSProgressHUD show];
            NSString *pageNumber = [NSString stringWithFormat:@"%ld",self.pageNumber];
            NSString *pageSize = [NSString stringWithFormat:@"%ld",self.pageSize];
            self.urlString = [NSString stringWithFormat:@"%@/recommend/selectTowDemandRecommend",kUrl];
            self.dict = @{
                          @"pageNumber":pageNumber,
                          @"pageSize":pageSize,
                          };
            XLog(@"self.dict:%@",self.dict);
            [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                XLog(@"HomeresponseObject:%@",responseObject);
                NSDictionary *date = [responseObject objectForKey:@"date"];
                NSArray *demandList =[date objectForKey:@"demandList"];
                NSArray *association =[date objectForKey:@"association"];
                for (NSDictionary *dict in demandList) {
                    SpecialRecommendationModel *model =[SpecialRecommendationModel mj_objectWithKeyValues:dict];
                    [self.subjectDemandArray addObject:model];
                }
                for (NSDictionary *dict in association) {
                    SpecialRecommendationModel *model =[SpecialRecommendationModel mj_objectWithKeyValues:dict];
                    [self.subjectServiceArray addObject:model];
                }
                NSIndexSet *set = [NSIndexSet indexSetWithIndex:2];
                [self.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationNone];
                [WSProgressHUD dismiss];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                XLog(@"error:%@",error);
            }];
        }
    }else if (indexPath.section == 3) {
        SubjectDemandServiceTabVC *homeVC = [[SubjectDemandServiceTabVC alloc]init];
        homeVC.navigationItem.title = @"最新需求&精选需求";
        homeVC.indexPath = indexPath;
        [self.navigationController pushViewController:homeVC animated:YES];
    }else if (indexPath.section == 5) {
        SubjectDemandServiceTabVC *homeVC = [[SubjectDemandServiceTabVC alloc]init];
        homeVC.navigationItem.title = @"最新服务&精选服务";
        homeVC.indexPath = indexPath;
        [self.navigationController pushViewController:homeVC animated:YES];
    }
    
}
#pragma mark-代理:显示联系人
-(void)demandCell:(DemandCell *)demandCell withClickBtn:(UIButton *)clickBtn withIndexPath:(NSIndexPath *)indexPath withHomeModel:(HomeModel *)homeModel
{
    if (self.changeInternet == 0) {
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请检查网络设置"];
    }else {
        if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]||[UserDefaultsHelper readAutoLogIn].length == 0) {
            [LogOutAccount presentOutAccount];
            [UIAlertViewWarningAccount showWarningAccount];
            [self reloadInternet];
        }else {
            self.dict = @{
                          @"userId":[UserDefaultsHelper readUid],
                          @"token":[UserDefaultsHelper readToken]
                          };
            XLog(@"self.dict:%@",self.dict);
            self.urlString = [NSString stringWithFormat:@"%@/user/checkToken",kUrl];
            [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
                if (status == 200) {
                    HomeModel *model = self.demandArray[indexPath.row];
                    model.show = clickBtn.selected;
                    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                }else {
                    [LogOutAccount presentOutAccount];
                    [UIAlertViewWarningAccount showWarningAccount];
                    [self reloadInternet];
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
            
        }
    }
}
#pragma mark-代理:收藏

- (void)demandCell:(DemandCell *)demandCell withCollectBtn:(UIButton *)clickBtn withIndexPath:(NSIndexPath *)indexPath withHomeModel:(HomeModel *)homeModel
{
    XLog(@"clickBtn:%d",clickBtn.selected);
    if (self.changeInternet == 0) {
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请检查网络设置"];
    }else {
        if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]) {
            [LogOutAccount presentOutAccount];
            [UIAlertViewWarningAccount showWarningAccount];
        }else if ([UserDefaultsHelper readAutoLogIn].length == 0) {
            [LogOutAccount presentOutAccount];
        }else{
            
            self.dict = @{
                          @"userId":[UserDefaultsHelper readUid],
                          @"token":[UserDefaultsHelper readToken]
                          };
            self.urlString = [NSString stringWithFormat:@"%@/user/checkToken",kUrl];
            [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                XLog(@"responseObject:%@",responseObject);
                //            NSString *message = [responseObject objectForKey:@"message"];
                NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
                if (status == 200) {
                    clickBtn.selected = !clickBtn.selected;
                    if (clickBtn.selected) {
                        homeModel.collectStatus = 1;
                    }else {
                        homeModel.collectStatus = 0;
                    }
                    NSString *ids = [NSString stringWithFormat:@"%ld",homeModel.id];
                    XLog(@"self.homeModel.id:%ld",homeModel.id);
                    NSString *collect = [NSString stringWithFormat:@"%d",clickBtn.selected];
                    self.dict = @{
                                  @"uid":[UserDefaultsHelper readUid],
                                  @"id":ids,
                                  @"type":@"1",
                                  @"status":collect,
                                  @"token":[UserDefaultsHelper readToken]
                                  };
                    XLog(@"self.dict:%@",self.dict);
                    [CustomeManager POSTWithURLIndex:34 parameters:self.dict success:^(NSDictionary *dict) {
                    } failure:^(NSError *error) {
                        
                    }];
                    
                }else {
                    [LogOutAccount presentOutAccount];
                    [UIAlertViewWarningAccount showWarningAccount];
                    [self reloadInternet];
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
        }
    }
}
#pragma mark-代理:收藏成功
-(void)insertCollection:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    NSString *message = [dict objectForKey:@"message"];
    [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
    
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 4) {
        HomeModel *model = self.demandArray[indexPath.row];
        DemandTheHallContentVC *demanVC = [[DemandTheHallContentVC alloc]init];
        demanVC.urlString = @"/demand/selectTwoDemand";
        demanVC.returnValueBlock = ^(NSInteger selected) {
            model.collectStatus = selected;
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        };
        demanVC.homeModel = model;
        [self.navigationController pushViewController:demanVC animated:YES];
    }else if (indexPath.section == 6) {
        ServiceContentTabVC *homeServiceVC = [[ServiceContentTabVC alloc]init];
         homeServiceVC.model = self.serveArray[indexPath.row];
        [self.navigationController pushViewController:homeServiceVC animated:YES];
    }
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    UIImage *image = [UIImage imageNamed:@"nonetwork"];
    return image;
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = @"请在iPhone的设置-无线局域网中允许商集使用WLAN与蜂窝移动网的应用";
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    // 设置所有字体大小为 #15
    [attStr addAttribute:NSFontAttributeName
                   value:[UIFont systemFontOfSize:15.0]
                   range:NSMakeRange(0, text.length)];
    // 设置所有字体颜色为浅灰色
    [attStr addAttribute:NSForegroundColorAttributeName
                   value:[UIColor lightGrayColor]
                   range:NSMakeRange(0, text.length)];
    // 设置指定4个字体为蓝色
    [attStr addAttribute:NSForegroundColorAttributeName
                   value:[UIColor colorWithRed:47/255.0 green:119/255.0 blue:246/255.0 alpha:1]
                   range:NSMakeRange(9, 2)];
    [attStr addAttribute:NSFontAttributeName
                   value:[UIFont systemFontOfSize:18.0]
                   range:NSMakeRange(9, 2)];
    return attStr;
}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    XLog(@"button");
}

/* Notifies when the dataset view was tapped: */
- (void)emptyDataSetDidTapView:(UIScrollView *)scrollView
{
//    [self reloadInternet];
    NSString * urlString = UIApplicationOpenSettingsURLString;

    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlString]]) {
        if ([[UIDevice currentDevice].systemVersion doubleValue] >= 10.0) {
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:nil];
            } else {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            }
        } else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            
        }
    }
}

@end
